import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import cache from '@/utils/cache'
import { TOKEN_KEY } from '@/utils/enums/cacheEnums'
import router, { filterAsyncRoutes } from '@/utils/router'
import { login, logout, getUserInfo } from '@/api/user'
import config from '@/config'
import { getToken, clearAuthInfo } from '@/utils/auth'
import { PageEnum } from '@/utils/enums/pageEnums'

interface UserState {
    token: string
    userInfo: Record<string, any>
    routes: RouteRecordRaw[]
    permissions: string[]
}

export const useUserStore = defineStore('user', {
    state: (): UserState => ({
        token: getToken() || '',
        userInfo: {},
        routes: [],
        permissions: [],
    }),
    getters: {
        // 获取token
        getToken(state: UserState) {
            return cache.get(TOKEN_KEY) ?? state.token
        }

    },
    actions: {

        resetState() {
            this.token = ''
            this.userInfo = {
                name: '',
            }
            this.routes = []
            this.permissions = []
        },
        // 登录
        async login(payload: any) {
            try {
                const { username, password } = payload;
                const res = await login({ username, password, terminal: config.terminal })
                this.token = res.token
                cache.set(TOKEN_KEY, this.token)
            } catch (error) {
                console.log(error)
            }
        }

        // 获取用户信息
        , getUserInfo() {
            return new Promise((resolve, reject) => {
                getUserInfo().then(res => {
                   
                    this.userInfo = res.userInfo
                    this.routes = filterAsyncRoutes(res.routes)
                    console.log(res.permission)
                    this.permissions = res.permission
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
                
            })
        },

        // 退出登录
        logout() {
            return new Promise((resolve, reject) => {
                logout().then(async res => {
                    this.token = '';
                    await router.push(PageEnum.LOGIN)
                    clearAuthInfo()
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        }
    },
})
